const Home = require('../models/home')
const { homeImgType, homeVoiceType } = require('../config/setting')
const fs = require('fs')
const path = require('path')

class HomeCtl{
    async findList(ctx) {
        let { fields = '', name = '', page = 1, perPage = 15, state = '' } = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
        page = Math.max(page * 1, 1) - 1
        perPage = Math.max(perPage * 1, 1)
        const reg = new RegExp(name, 'ig')
        const states = new RegExp(state)
        ctx.body = await Home.find({
            name: reg,
            state: states
        }).select(selectFields).limit(perPage).skip(perPage * page)
    }
    async findById(ctx) {
        const {fields=''} = ctx.query
        const id = ctx.params.id
        const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
        const populateStr = fields.split(';').filter(f => f).map(f => {
            if (f === 'author') {
                return 'author'
            } else {
                return ''
            }
        })
        const option = await Home.findById(id)
            .select(selectFields)
            .populate(populateStr)
        ctx.body = option
    }
    async create(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true }
        })
        const { name } = ctx.request.body
        const namer = await Home.findOne({ name })
        if (namer) {
            ctx.throw(409, '该类型已存在')
        } else {
            const option = await new Home({
                ...ctx.request.body,
                author: ctx.state.user._id
            }).save()
            ctx.body = option
        }
    }
    async update(ctx) {
        await ctx.state.option.update(ctx.request.body)
        ctx.body = ctx.state.option
    }
    async uploadImg(ctx) {
        const file = ctx.request.files.file
        let tf = false
        let suffix
        let i = 0
        const paths = path.join(__dirname, '../public/uploads', '/home')
        for (const item of homeImgType) {
            if (item === file.type) {
                tf = true
                suffix = new RegExp(/(.[^\/]*)$/ig).exec(file.type)[0].replace('/', '')
                break
            }
        }
        if (tf) {
            for (const item of homeImgType) {
                const str = new RegExp(/(.[^\/]*)$/ig).exec(item)[0].replace('/', '')
                const fileName = `${paths}\\${ctx.params.id}.${str}`
                fs.access(fileName, (err) => {
                    if (err) {
                        i++
                        if (i === homeImgType.length) {
                            const avatarPath = path.resolve(paths, `./${ctx.params.id}.${suffix}`)
                            const readStream = fs.createReadStream(file.path)
                            const writeStream = fs.createWriteStream(avatarPath)
                            readStream.pipe(writeStream)
                        }
                    } else {
                        fs.unlink(fileName, (error) =>{
                            if (error) {
                                return
                            }
                            const avatarPath = path.resolve(paths, `./${ctx.params.id}.${suffix}`)
                            const readStream = fs.createReadStream(file.path)
                            const writeStream = fs.createWriteStream(avatarPath)
                            readStream.pipe(writeStream)
                        })
                    }
                })
            }
            const url = `${ctx.origin}/uploads/home/${ctx.params.id}.${suffix}`
            await ctx.state.option.update({img: url})
            ctx.body = { url }
        } else {
            ctx.throw(415, '不支持该类型格式的图片')
        }  
    }
    async uploadVoice(ctx) {
        const file = ctx.request.files.file
        let tf = false
        let suffix
        let i = 0
        const paths = path.join(__dirname, '../public/uploads', '/home/voice')
        for (const item of homeVoiceType) {
            if (item === file.type) {
                tf = true
                suffix = new RegExp(/(.[^\/]*)$/ig).exec(file.type)[0].replace('/', '')
                break
            }
        }
        if (tf) {
            for (const item of homeVoiceType) {
                const str = new RegExp(/(.[^\/]*)$/ig).exec(item)[0].replace('/', '')
                const fileName = `${paths}\\${ctx.params.id}.${str}`
                fs.access(fileName, (err) => {
                    if (err) {
                        i++
                        if (i === homeVoiceType.length) {
                            const avatarPath = path.resolve(paths, `./${ctx.params.id}.${suffix}`)
                            const readStream = fs.createReadStream(file.path)
                            const writeStream = fs.createWriteStream(avatarPath)
                            readStream.pipe(writeStream)
                        }
                    } else {
                        fs.unlink(fileName, (error) =>{
                            if (error) {
                                return
                            }
                            const avatarPath = path.resolve(paths, `./${ctx.params.id}.${suffix}`)
                            const readStream = fs.createReadStream(file.path)
                            const writeStream = fs.createWriteStream(avatarPath)
                            readStream.pipe(writeStream)
                        })
                    }
                })
            }
            const url = `${ctx.origin}/uploads/home/voice/${ctx.params.id}.${suffix}`
            await ctx.state.option.update({voice: url})
            ctx.body = { url }
        } else {
            ctx.throw(415, '不支持该类型格式的音频')
        }
    }
    async checkOptionExist(ctx, next) { //检查选项是否存在
        const id = ctx.params.id
        const option = await Home.findById(id)
        if (option) {
            ctx.state.option = option
            await next()
        } else {
            ctx.throw(404, '该选项不存在')
        }
    }
    async delete(ctx) {
        const id = ctx.params.id
        await Home.findByIdAndRemove(id)
        ctx.status = 204
    }
}

module.exports = new HomeCtl